/*
 * @Date: 2020-11-26 20:25:19
 * @LastEditors: 小枫
 * @description: description
 * @LastEditTime: 2020-11-26 20:41:44
 * @FilePath: \stu-nest\src\common\guards\roles.guard.ts
 */
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';
import { Reflector } from '@nestjs/core';

@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    if (!roles) {
      return true;
    }
    const request = context.switchToHttp().getRequest();
    const { user } = request.query;
    return !!roles.find((role) => role === user);
  }
}
